import { defineComponent, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import {assignDeep, isEmpty, setByPath} from "@/utils/common";
//全局公共插槽
import customSlots from "@/slots"
import axios from "@/axios";
import MyForm from "../MyForm";
import SelectGridUtil from "@/utils/SelectGridUtil";

export default defineComponent({
    name: "Sjdx",
    components: { MyForm },
    props: {
        params: {
            type: Object,
        },
        slots: {
            type: Object
        },
        activeSjdx:{
            type: String,
        }
    },
    /**
     * 监测路由变化
     * @param to 目标路由
     * @param from 来源路由
     * @returns {Promise<void>}
     */
    beforeRouteUpdate: (to, from) => {
    },
    emits: ["close","setSgUtil"],
    /**
     * 所有页面入口，该组件会缓存各数据对象基础信息，对各页面进行复用
     * @param props
     * @param context
     * @returns {Promise<{myData: UnwrapNestedRefs<{activeSjdx: string, dxjcxx: {}}>}>}
     */
    setup: async (props, context) => {

        const slotTemplate = context.slots
        const route = useRoute() as any;
        const myData = reactive({
            /**
             * 对象基础信息集合<key,dxjcxx>
             */
            dxjcxx: {},
            /**
             * 活动的数据对象key
             */
            activeSjdx: "",
        });
        /**
         * 根据请求参数进行对象基础信息的加载
         * @param query 查询参数
         * @returns {Promise<void>}
         */
        const initPage = (query: any) => {
            let dxjcxx = { sys: {} as any, sjdx: {} as any, yobj: {} as any, fields: {} as any }
            for (let key in query) {
                if(!isEmpty(key)){
                    setByPath(dxjcxx, key, query[key]);
                }
            }
            if (!dxjcxx.sys.cllx) {
                dxjcxx.sys.cllx = "select";
            }
            const cacheKey = dxjcxx.sjdx.dxdm + dxjcxx.sjdx.id + dxjcxx.sys.authCode;
            if (!cacheKey) {
                ElMessage.error("传入数据对象信息");
            } else if (!myData.dxjcxx[cacheKey]) {
                //加载对象基础信息
                let params = JSON.parse(JSON.stringify(dxjcxx))
                params.sys.cllx = "dxjcxx"
                axios.post(params, { ctdy: false }).then((rep) => {
                    assignDeep(rep.data, dxjcxx);
                    myData.dxjcxx[cacheKey] = rep.data;
                    //设置当前显示的组件
                    myData.activeSjdx = cacheKey;
                }).catch((e) => {
                    console.log("获取基础信息失败", e)
                })
            } else {
                //将当前传入的部分定制信息设置进去传入子组件
                myData.dxjcxx[cacheKey].sys.cllx = dxjcxx.sys.cllx;
                myData.dxjcxx[cacheKey].yobj = dxjcxx.yobj;
                //设置当前显示的组件
                myData.activeSjdx = cacheKey;
            }
        }
        // 当参数更改时获取用户信息
        watch(
            () => route.query,
            async newQuery => {
                if (route.path.startsWith("/home/sjdx") && Object.keys(newQuery).length > 0 && !props.params) {
                    await initPage(newQuery);
                }
            }
        )

        watch(
            () => route.meta,
            async newQuery => {
                let cdkz = {}
                if (route.meta.dzlx === '03') {
                    if (route.meta.extend && route.meta.extend.cdkz) {
                        cdkz = route.meta.extend.cdkz
                    }
                    const base = { "sys.authCode": route.meta.authCode, "pathName": route.meta.title }
                    await initPage({ ...base, ...cdkz })
                }
            }
        )

        watch(
            () => props.params,
            async newQuery => {
                if (newQuery && Object.keys(newQuery).length > 0) {
                    await initPage(newQuery);
                }
            }
        )
        watch(
            () => props.activeSjdx,
            async activeSjdx => {
                if(activeSjdx){
                    myData.activeSjdx = activeSjdx
                }
            }
        )
        //初次进入调用
        if (props.params) {
            await initPage(props.params);
        } else if (route.meta && route.meta.authCode) {
            let cdkz = {}
            if (route.meta.dzlx !== '01') {
                if (route.meta.extend && route.meta.extend.cdkz) {
                    cdkz = route.meta.extend.cdkz
                }
                const base = { "sys.authCode": route.meta.authCode, "pathName": route.meta.title }
                await initPage({ ...base, ...cdkz })
            }
        } else {
            await initPage(route.query);
        }
        /**
         * 表单页面关闭事件
         * @param sfsxym 是否刷新页面
         */
        const close = (sfsxym: any) => {
            console.info(sfsxym, this)
            context.emit("close", sfsxym, this);
        }
        const setSgUtil = (sgUtil:SelectGridUtil)=>{
            context.emit("setSgUtil", sgUtil)
        }

        return {
            myData,
            slotTemplate,
            close,
            setSgUtil
        }
    },
    render() {
        return (
            Object.keys(this.myData.dxjcxx).length > 0 ? Object.keys(this.myData.dxjcxx).map((item: any, index: number) => {
                // console.log({ ...customSlots, ...this.slots, ...this.slotTemplate })
                return (
                    <MyForm key={item} slots={{ ...customSlots, ...this.slots, ...this.slotTemplate }} dxjcxx={this.myData.dxjcxx[item]}
                        v-show={item === this.myData.activeSjdx}
                        onClose={this.close} onSetSgUtil={this.setSgUtil}></MyForm>
                )
            }) : null
        )

    }
});
